<script setup lang="ts">
import { BaseApi } from "@/apis/base.api";
import { UtilTool } from "@webxue/common";
import { computed, onMounted, reactive } from 'vue';
import { useWebxRouteTabs } from "@webxue/vue3-antdv-ui";
import useForm from "@/hooks/useForm";
import useCusRouter from "@/hooks/useCusRouter";
import EventEmitTool from "@/utils/tools/event-emit.tool";

// 获取路由属性
const { router, routeQuery } = useCusRouter({
  queryKeys: [
    // 菜单组id
    "menuGroupId",
    // 是否只读
    "readonly"
  ]
});
const { addParentTab } = useWebxRouteTabs({ router });
// 获取详情hook
const { detailInfo, formRef, formState, onValidateFields, getFormRules } = useForm({
  // 获取表单数据
  formState: {} as Record<string, any>,
  // 获取详情数据
  async onInit() {
    // 数据初始化
    formState.value.status = 1;

    // 获取详情
    if (!routeQuery.value.menuGroupId) return false;
    const response = await BaseApi.menuGroup.find({ id: routeQuery.value.menuGroupId });
    // 数据回显
    formState.value = UtilTool.lodash.cloneDeep(response.data);
    // 关联菜单回显
    menuObj.checkedKeys.checked = formState.value.menuList?.map(menu => menu.menuId) || [];
    return Promise.resolve(response);
  },
  // 表单校验成功回调
  async onValidateSuccess(values) {
    // 响应结果
    let response: Partial<ResponseData> = {};
    // 请求参数
    const requestBody: Record<string, any> = {
      name: values.name,
      remark: values.remark,
      menuIds:menuObj.checkedKeys.checked.join(",")
    };
    if (routeQuery.value.menuGroupId) {
      // 编辑
      response = await BaseApi.menuGroup.update({
        ...requestBody,
        id: routeQuery.value.menuGroupId
      });
    } else {
      // 新增
      response = await BaseApi.menuGroup.save({
        ...requestBody
      });
    }
    if (response.success) {
      addParentTab();
    }
  }
});
// 获取菜单
const menuObj = reactive({
  // 菜单树
  menuTree: [],
  // 勾选的菜单
  checkedKeys: {
    checked:[],
    halfChecked:[]
  },
  // 菜单树扁平化
  menuTreeFlat: computed(() => UtilTool.flatArr(menuObj.menuTree, "children")),
  // 设置禁止勾选菜单
  setDisabledMenu(menuTree){
    menuTree.forEach(menu => {
      if(menu.isCommon === 1) {
        menu.disabled = true;
      }
      if(menu.children?.length) {
        menuObj.setDisabledMenu(menu.children);
      }
    })
  },
  // 设置菜单树
  async setMenuTree() {
    const response = await BaseApi.menu.tree({});
    menuObj.menuTree = response.data;
    // 默认选中公共菜单
    // const commonMenu = menuObj.menuTreeFlat.filter(menu => menu.isCommon === 1);
    // menuObj.checkedKeys = commonMenu.map(menu => menu.id);
    // 递归设置菜单禁用
    // menuObj.setDisabledMenu(menuObj.menuTree);
  }
});

// form保存回调
EventEmitTool.on("FORM:SAVE", () => {
  // 开始校验
  onValidateFields();
});

onMounted(async () => {
  await menuObj.setMenuTree();
});
</script>

<template>
  <div>
    <WebxForm ref="formRef" :model="formState" :readonly="!!routeQuery.readonly">
      <div class="flex flex-col gap-2">
        <WebxCard :titleProps="{ title: '菜单组维护' }">
          <ARow class="px-2 pb-4" :gutter="10">
            <ACol :span="8">
              <WebxFormItem
                label="菜单组名称"
                name="name"
                :rules="[{ required: true, message: '请输入菜单组名称' }]"
              >
                <AInput v-model:value="formState.name" placeholder="请输入菜单组名称" />
                <template #readonly>{{ formState.name }}</template>
              </WebxFormItem>
            </ACol>
            <ACol :span="8">
              <WebxFormItem tooltip="前端工程根据project名称和菜单组的code字段进行匹配获取菜单"
                label="菜单组标识"
                name="code"
                :rules="[{ required: true, message: '请输入菜单组标识' }]"
              >
                <AInput v-model:value="formState.code" placeholder="请输入菜单组标识" :disabled="!!routeQuery.menuGroupId" />
                <template #readonly>{{ formState.code }}</template>
              </WebxFormItem>
            </ACol>
            <ACol :span="24">
              <WebxFormItem label="备注" name="remark">
                <ATextarea
                  v-model:value="formState.remark"
                  placeholder="请输入备注"
                  :autoSize="{ minRows: 4, maxRows: 4 }"
                />
                <template #readonly>{{ formState.remark }}</template>
              </WebxFormItem>
            </ACol>
          </ARow>
        </WebxCard>
        <WebxCard :titleProps="{ title: '关联菜单' }">
          <WebxFormItem name="menuIds">
            <ATree
              checkable
              checkStrictly
              defaultExpandAll
              :selectable="false"
              :key="menuObj.menuTree.length"
              v-model:checkedKeys="menuObj.checkedKeys"
              :treeData="menuObj.menuTree"
              :fieldNames="{ title:'name', key:'id', children: 'children' }"
             />
          </WebxFormItem>
        </WebxCard>
      </div>
    </WebxForm>
  </div>
</template>

<style scoped lang="less">
// form-item的label等宽
:deep(.ant-form-item-label) { width: 120px; }
// tree的checkbox居中
:deep(.ant-tree .ant-tree-checkbox) { margin: 0; }
</style>
